package loan.calc.calculator.impl;

import loan.calc.exception.CalcualatorException;
import loan.calc.constant.dict.RepayFrequencyTypeEnum;
import loan.calc.dto.LoanDTO;
import org.springframework.stereotype.Component;

import java.time.temporal.ChronoUnit;

@Component("repaySegmentFrequencyCalculator")
public class LoanRepaymentSegmentFrequencyCalculator extends AbstractCalculator {

    private static final Integer SORT_CODE = 100;

    @Override
    public Integer calculatorSort() {
        return SORT_CODE;
    }

    @Override
    public String calculatorName() {
        return "还款区段还款频率校验及填充";
    }

    @Override
    public void calculate(LoanDTO loan) {
        loan.getLoanRepaySegmentList().forEach(loanRepaymentSegment -> {
            RepayFrequencyTypeEnum repayFrequencyType = loanRepaymentSegment.getRepayFrequencyType();
            CalcualatorException.requireNonNull(repayFrequencyType,"计算器参数异常，获取还款区段[还款频率类型为空]");
            if (!repayFrequencyType.equals(RepayFrequencyTypeEnum.ASSIGN)) {
                ChronoUnit repayFrequencyUnit = repayFrequencyType.getFrequencyUnit();
                Integer repayFrequency = repayFrequencyType.getRepayFrequency();
                loanRepaymentSegment.setRepayFrequencyUnit(repayFrequencyUnit);
                loanRepaymentSegment.setRepayFrequency(repayFrequency);
                printRepaymentSegmentDebugLog(loanRepaymentSegment, "还款频率,周期单位,周期分别为" + String.join(",", repayFrequencyType.getDescription(), repayFrequencyUnit.toString(), repayFrequency.toString()));
            } else {
                Integer repayFrequency = loanRepaymentSegment.getRepayFrequency();
                ChronoUnit repayFrequencyUnit = loanRepaymentSegment.getRepayFrequencyUnit();
                CalcualatorException.isTrue(repayFrequencyUnit != null && repayFrequency != null, "计算器参数异常，当还款频率类型为[指定周期]时，[还款频率单位]或[还款频率数量]不能为空");
                CalcualatorException.isTrue(repayFrequency> 1 && repayFrequency<=366, "计算器参数异常，当还款频率类型为[指定周期]时，[还款频率数量]不合法");
            }
        });
    }
}
